﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using PairingMatrix.Common.Enum;
using PairingMatrix.Model;
using PairingMatrix.ViewModel;
using System.Linq;

namespace PairingMatrix.View.Behavior
{
    public class DragTeamMemberCardBehavior : Behavior<TeamMemberCardControl>
    {
        private Point _mouseStartPosition;
        private ContentPresenter _parent;
        private Canvas _canvas;
        private bool _isMouseCaptured = false;
        private IProjectCardViewModel _nearestProjectCard = null;
        private TeamMemberCardViewModel _teamMemberCardViewModel;
                    
        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
            {
                _teamMemberCardViewModel = (TeamMemberCardViewModel)AssociatedObject.DataContext;
                _teamMemberCardViewModel.PropertyChanged += TeamMemberCard_PropertyChanged;
            };

            AssociatedObject.MouseLeftButtonDown += (sender, e) =>
            {
                if(_teamMemberCardViewModel.ArrangeCardToShowStatistics || _teamMemberCardViewModel.ArrangeCardToShowIceCreamMeter)
                    return;

                if (_parent == null)
                {
                    _parent = (ContentPresenter)VisualTreeHelper.GetParent(AssociatedObject);
                    _canvas = (Canvas)VisualTreeHelper.GetParent(_parent);
                }
                _mouseStartPosition = e.GetPosition(_canvas);
                AssociatedObject.CaptureMouse();
                _isMouseCaptured = true;

                Registry.SeletedTeamMemberId = _teamMemberCardViewModel.Id;
                ((ICardWallViewModel)ControlRegistry.CardWallControl.DataContext).TeamMembers.ToList().ForEach(t => t.ShowNumberOfDaysPairedWithSelectedTeamMember = true);

            };

            var cardWallControl = ControlRegistry.CardWallControl;
            AssociatedObject.MouseLeftButtonUp += (sender, e) =>
            {

                if (_teamMemberCardViewModel.ArrangeCardToShowStatistics || _teamMemberCardViewModel.ArrangeCardToShowIceCreamMeter)
                    return;

                AssociatedObject.ReleaseMouseCapture();
                _isMouseCaptured = false;

                _teamMemberCardViewModel.Position = new Point(Canvas.GetLeft(_parent), Canvas.GetTop(_parent));

                var cardWallViewModel = ((ICardWallViewModel)cardWallControl.DataContext);
                if (_nearestProjectCard != null)
                {
                    cardWallViewModel.AttachTeamMemberToProjectCard((ITeamMemberCardViewModel) AssociatedObject.DataContext, _nearestProjectCard);
                }
                else
                    cardWallViewModel.DetachTeamMemberFromAllProjectCards((ITeamMemberCardViewModel)AssociatedObject.DataContext);

                foreach (var projectCard in cardWallViewModel.ProjectCards)
                {
                    projectCard.ShowHighlighted = false;
                }
                ((ICardWallViewModel)ControlRegistry.CardWallControl.DataContext).TeamMembers.ToList().ForEach(t => t.ShowNumberOfDaysPairedWithSelectedTeamMember = false);
            };

            AssociatedObject.MouseMove += (sender, e) =>
            {
                if (_teamMemberCardViewModel.ArrangeCardToShowStatistics || _teamMemberCardViewModel.ArrangeCardToShowIceCreamMeter)
                    return;

                if (_isMouseCaptured)
                {
                    if (_parent == null)
                    {
                        _parent = (ContentPresenter)VisualTreeHelper.GetParent(AssociatedObject);
                        _canvas = (Canvas)VisualTreeHelper.GetParent(_parent);
                    }
                    var pointOnCanvas = e.GetPosition(_canvas);
                    var point = new Point(pointOnCanvas.X - _mouseStartPosition.X, pointOnCanvas.Y - _mouseStartPosition.Y);

                    var currentTop = Canvas.GetTop(_parent);
                    var currentLeft = Canvas.GetLeft(_parent);
                    SetTeamMemberControlInPosition(currentLeft + point.X, currentTop + point.Y);
                    
                    _mouseStartPosition = pointOnCanvas;

                    var centerPointXOfTeamMemberCard = currentLeft + _parent.ActualWidth/2;
                    var centerPointYOfTeamMemberCard = currentTop + _parent.ActualHeight/2;

                    double minDist = 10000;
                    var cardWallViewModel = ((ICardWallViewModel)cardWallControl.DataContext);
                    if(_nearestProjectCard != null)
                        _nearestProjectCard.ShowHighlighted = false;
                    _nearestProjectCard = null;
                    var projectCards = cardWallViewModel.ProjectCards.Where(c => c.IsCardVisibleInCurrentWall);
                    foreach (var projectCard in projectCards)
                    {
                        if (projectCard.PrimaryCard != null)
                            continue;

                        var x = projectCard.CenterPoint.X - centerPointXOfTeamMemberCard;
                        var y = projectCard.CenterPoint.Y - centerPointYOfTeamMemberCard;
                        var currentDist = Math.Sqrt(x*x + y*y);
                        if (currentDist < minDist && currentDist < 180 && projectCard.CanAcceptMoreTeamMember())
                        {
                            minDist = currentDist;
                            _nearestProjectCard = projectCard;
                        }
                    }

                    if(_nearestProjectCard != null)
                        _nearestProjectCard.ShowHighlighted = true;
                }
            };
        }

        void TeamMemberCard_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Position")
            {
                SetTeamMemberControlInPosition(_teamMemberCardViewModel.Position.X, _teamMemberCardViewModel.Position.Y);
            }
        }

        private void SetTeamMemberControlInPosition(double x, double y)
        {
            if (_parent == null)
            {
                _parent = (ContentPresenter)VisualTreeHelper.GetParent(AssociatedObject);
                _canvas = (Canvas)VisualTreeHelper.GetParent(_parent);
            }
            Canvas.SetLeft(_parent, x);
            Canvas.SetTop(_parent, y);
        }
    }
}
